using System;
using System.Collections.Generic;
using ResourceLoader.Extensions;

namespace ResourceLoader.DeserializeTool
{
    public class DeserializableHeader
    {
        /// <summary>
        /// 根据二进制数组,返回字典
        /// </summary>
        /// <param name="seriaBytes"></param>
        /// <returns></returns>
        public static Dictionary<string, ResourceInfo> ToDictionary(byte[] seriaBytes)
        {
            Dictionary<string, ResourceInfo> resultDictionary = new Dictionary<string, ResourceInfo>();
            long bytesIndex = 0; //二进制索引
            long longLength = 8;
            while (bytesIndex < seriaBytes.Length)
            {
                //index 文件位置索引
                //length 文件长度
                //filePathLength 文件路径信息长度
                //filePath 文件路径信息
                long index = BitConverter.ToInt64(seriaBytes.SubArray(bytesIndex, longLength), 0);
                bytesIndex += longLength;
                long length = BitConverter.ToInt64(seriaBytes.SubArray(bytesIndex, longLength), 0);
                bytesIndex += longLength;
                long filePathLength =
                    BitConverter.ToInt64(seriaBytes.SubArray(bytesIndex, longLength), 0);
                bytesIndex += longLength;
                string filePath =
                    System.Text.Encoding.UTF8.GetString(seriaBytes.SubArray(bytesIndex, filePathLength));
                ResourceInfo resourceInfo;
                resourceInfo.Index = index;
                resourceInfo.Length = length;
                var paths = filePath.Split('/');
                resourceInfo.FileName = paths[paths.LongLength - 1];
                resultDictionary.Add(filePath, resourceInfo);
                bytesIndex += filePathLength;
            }

            return resultDictionary;
        }
    }
}